
let mixins = require('../utils/mixins');
let EventEmitter = require('eventemitter3');
let colorUtils = require('../utils/colorUtils');

const DefaultOptions = {
    r: 255,
    g: 255,
    b: 255,
    name:'颜色'
};

const templateDiv = `
    <span id="name"></span>
    <input type="color" id="color">
`;

class ColorChoose {
    constructor(options = {}) {
        mixins(options,DefaultOptions);

        this._r = this._g = this._b  = 0;

        let r = options.r;
        let g = options.g;
        let b = options.b;
        let name = options.name;

        this.element = globalThis.document.createElement('div');
        this.element.innerHTML = templateDiv;

        this.nameEl = this.element.querySelector('#name');
        this.nameEl.innerText = name;

        this.colorEl = this.element.querySelector('#color');
        this.colorEl.addEventListener('change',this.onUIClorChanged.bind(this),false);

        // init events
        this.ee = new EventEmitter();
        this.ee.on('rgb',this.onDataColorChanged,this);

        this.setRGB(r,g,b);
    }

    // data -> ui
    onDataColorChanged(){
        this.colorEl.value = colorUtils.stringifyRgb(this._r,this._g,this._b);
    }

    // ui->data
    onUIClorChanged(){
        let [r,g,b] = colorUtils.parseRbgStr(this.colorEl.value);
        this.setRGB(r,g,b);
    }

    setRGB(r,g,b){
        this._r = r;
        this._g = g;
        this._b = b;
        this.ee.emit('rgb');
    }

    setR(newValue){
        this._r = newValue;
        this.ee.emit('rgb');
        return this;
    }
    setG(newValue){
        this._g = newValue;
        this.ee.emit('rgb');
        return this;
    }
    setB(newValue){
        this._b = newValue;
        this.ee.emit('rgb');
        return this;
    }

    getR(){return this._r;}
    getG(){return this._g;}
    getB(){return this._b;}
}


module.exports = ColorChoose;
